using Aliphant.Mvvm.XEvent.Ioc;
using GrpcClient.Assets.CustomModels;
using GrpcClient.Managers;
using System.Windows;
using System.Windows.Controls;

namespace GrpcClient.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : CustomWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            BackToLoginEvent += OnBackToLogin;
            OpenUserCenterEvent += OnOpenUserCenter;
            OpenSettingEvent += OnOpenSetting;
            MinimizeWindowEvent += OnMinimizeWindow;

            XContainerLocator.Instance.RegisterRegion<ContentControl>(this.body, "body");
            XContainerLocator.Instance.RegisterRegion<ContentControl>(this.navigate, "navigate");
        }

        private void OnMinimizeWindow()
        {
            ResourceManager.Instance.LastState = this.WindowState;
        }

        private void OnOpenSetting()
        {
            XContainerLocator.Instance.NavigateTo("body", "setting");
        }

        private void OnOpenUserCenter()
        {
            XContainerLocator.Instance.NavigateTo("body", "userCenter");
        }

        private async void OnBackToLogin()
        {
            var res = MessageBox.Show("是否登出", "客户端", MessageBoxButton.YesNo);
            if (res == MessageBoxResult.No) return;

            await UserManager.Instance.LoginOut();
            if (!UserManager.Instance.IsLogin)
            {
                LoginOutCallback();
            }
        }

        private void LoginOutCallback()
        {
            Application.Current.MainWindow = App.loading;
            Application.Current.MainWindow.Show();

            if (App.topThumb != null)
            {
                App.topThumb.Close();
                App.topThumb = null;
            }

            this.Close();
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            XContainerLocator.Instance.CancelRegister("body");

            if (Application.Current.MainWindow == null)
            {
                Application.Current.Shutdown();
            }
        }


        private void CustomWindow_Loaded(object sender, RoutedEventArgs e)
        {
            XContainerLocator.Instance.NavigateTo("navigate", "navigationBar");
        }
    }
}
